package com.csjbot.blackgaga.feature.vipcenter;

import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;

import com.alibaba.android.arouter.facade.annotation.Route;
import com.csjbot.blackgaga.R;
import com.csjbot.blackgaga.ai.VipCenterAI;
import com.csjbot.blackgaga.base.BaseFullScreenActivity;
import com.csjbot.blackgaga.base.BasePresenter;
import com.csjbot.blackgaga.core.RobotManager;
import com.csjbot.blackgaga.model.tcp.factory.ServerFactory;
import com.csjbot.blackgaga.router.BRouterPath;
import com.csjbot.blackgaga.util.BlackgagaLogger;
import com.csjbot.blackgaga.util.QRCodeUtil;
import com.csjbot.coshandler.listener.OnCameraListener;
import com.csjbot.coshandler.listener.OnFaceSaveListener;
import com.csjbot.coshandler.listener.OnSnapshotoListener;

import org.json.JSONException;
import org.json.JSONObject;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * Created by xiasuhuei321 on 2017/10/18.
 * author:luo
 * e-mail:xiasuhuei321@163.com
 */

@Route(path = BRouterPath.VIP_CENTER)
public class VipCenterActivity extends BaseFullScreenActivity {
    public static final String QRCODE = "qrcode";

    private ImageView iv_qrcode;

    VipCenterAI mAI;

    RobotManager mRobotManager;

    boolean mPausePreview;

    boolean mCorrectPhoto;

    Drawable mPhoto;

    @BindView(R.id.iv_preview)
    ImageView iv_preview;

    @BindView(R.id.iv_preview_photo)
    ImageView iv_preview_photo;

    @BindView(R.id.ll_register)
    LinearLayout ll_register;

    @BindView(R.id.ll_register_success)
    LinearLayout ll_register_success;

    @BindView(R.id.ll_take_photo)
    LinearLayout ll_take_photo;

    @BindView(R.id.ll_complete_and_retake)
    LinearLayout ll_complete_and_retake;

    @BindView(R.id.bt_complete)
    Button bt_complete;

    @BindView(R.id.bt_retake)
    Button bt_retake;

    @BindView(R.id.bt_take_photo)
    Button bt_take_photo;

    @BindView(R.id.et_name)
    EditText et_name;

    volatile boolean isTakeIn;

    @Override
    protected BasePresenter getPresenter() {
        return null;
    }

    @Override
    public int getLayoutId() {
        return R.layout.activity_vip;
    }

    @Override
    public void afterViewCreated(Bundle savedInstanceState) {
        iv_qrcode = (ImageView) findViewById(R.id.iv_qrcode);
        Intent intent = getIntent();
        getTitleView().setBackVisibility(View.VISIBLE);
        String qrcode = intent.getStringExtra(QRCODE);
        QRCodeUtil.getQRCodeAsync("这是一个测试二维码", 800, new QRCodeUtil.ReadyListener() {
            @Override
            public void codeReady(Bitmap bitmap) {
                runOnUiThread(() -> iv_qrcode.setImageBitmap(bitmap));

            }
        });
//        new AwesomeQRCode.Renderer()
//                .size(800).margin(20)
////                .contents(qrcode)
//                .roundedDots(true)
//                .contents("这是一个测试二维码")
//                .renderAsync(new AwesomeQRCode.Callback() {
//                    @Override
//                    public void onRendered(AwesomeQRCode.Renderer renderer, Bitmap bitmap) {
//                        runOnUiThread(() -> iv_qrcode.setImageBitmap(bitmap));
//                    }
//
//                    @Override
//                    public void onError(AwesomeQRCode.Renderer renderer, Exception e) {
//                        e.printStackTrace();
//                    }
//                });
    }

    @Override
    public boolean isOpenChat() {
        return true;
    }

    @Override
    public boolean isOpenTitle() {
        return true;
    }

    @Override
    public void init() {
        super.init();
        mAI = VipCenterAI.newInstance();
        mAI.initAI(this);

        mRobotManager = RobotManager.getInstance();
        mRobotManager.addListener(new OnCameraListener() {
            @Override
            public void response(Bitmap reponse) {
                if (!mPausePreview) {
                    runOnUiThread(() -> iv_preview.setImageBitmap(reponse));
                }

            }
        });
        mRobotManager.addListener(new OnSnapshotoListener() {
            @Override
            public void response(String response) {
                try {
                    BlackgagaLogger.debug("response:" + response);
                    int errorCode = new JSONObject(response).getInt("error_code");
                    BlackgagaLogger.debug("error_code:-------------------->" + errorCode);
                    if (errorCode == 0) {
                        mCorrectPhoto = true;
                    }
                } catch (JSONException e) {
                    BlackgagaLogger.error(e.toString());
                }
            }
        });
        mRobotManager.cameraConnect(this);
    }

    @Override
    protected CharSequence initChineseSpeakText() {
        return getString(R.string.member_register_speak_text);
    }

    @Override
    protected CharSequence initEnglishSpeakText() {
        return getString(R.string.member_register_speak_text);
    }

    @OnClick(R.id.bt_take_photo)
    public void takePhoto() {
        if (isTakeIn) {
            return;
        }
        new Thread(() -> {
            isTakeIn = true;
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            runOnUiThread(() -> {
                speak(getString(R.string.three));
                setRobotChatMsg(getString(R.string.three));
            });
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            runOnUiThread(() -> {
                speak(getString(R.string.two));
                setRobotChatMsg(getString(R.string.two));
            });
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            runOnUiThread(() -> {
                speak(getString(R.string.num_one));
                setRobotChatMsg(getString(R.string.num_one));
            });
            try {
                Thread.sleep(800);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            runOnUiThread(() -> {
                mPausePreview = true;
                mPhoto = iv_preview.getDrawable();
                ll_complete_and_retake.setVisibility(View.VISIBLE);
                bt_take_photo.setVisibility(View.GONE);
                ServerFactory.getFaceInstance().snapshot();

                isTakeIn = false;
            });
        }).start();
    }

    @OnClick(R.id.bt_complete)
    public void complete() {
        if (!mCorrectPhoto) {
            String errorText = getString(R.string.retake_photo_speak_text);
            speak(errorText);
            setRobotChatMsg(errorText);
            return;
        }
        mCorrectPhoto = false;
        ll_take_photo.setVisibility(View.GONE);
        ll_register.setVisibility(View.VISIBLE);

        iv_preview_photo.setImageDrawable(mPhoto);
    }

    @OnClick(R.id.bt_retake)
    public void retake() {
        mPausePreview = false;
        ll_complete_and_retake.setVisibility(View.INVISIBLE);
        new Thread(() -> {


            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            runOnUiThread(() -> {
                speak(getString(R.string.three));
                setRobotChatMsg(getString(R.string.three));
            });
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            runOnUiThread(() -> {
                speak(getString(R.string.two));
                setRobotChatMsg(getString(R.string.two));
            });
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            runOnUiThread(() -> {
                speak(getString(R.string.num_one));
                setRobotChatMsg(getString(R.string.num_one));
            });
            try {
                Thread.sleep(800);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            runOnUiThread(() -> {
                mPausePreview = true;
                mPhoto = iv_preview.getDrawable();
                ll_complete_and_retake.setVisibility(View.VISIBLE);
                ServerFactory.getFaceInstance().snapshot();
            });

        }).start();
    }

    @OnClick(R.id.bt_ok)
    public void ok() {
        String name = et_name.getText().toString().trim();
        if (TextUtils.isEmpty(name)) {
            String speakText = getString(R.string.input_name);
            speak(speakText);
            setRobotChatMsg(speakText);
            return;
        }
        mRobotManager.addListener(new OnFaceSaveListener() {
            @Override
            public void response(String response) {
                try {
                    BlackgagaLogger.debug("response:" + response);
                    int errorCode = new JSONObject(response).getInt("error_code");
                    BlackgagaLogger.debug("error_code:-------------------->" + errorCode);
                    if (errorCode == 0) {
                        runOnUiThread(() -> {
                            ll_register.setVisibility(View.GONE);
                            ll_register_success.setVisibility(View.VISIBLE);
                            String text = getString(R.string.register_success_speak_text);
                            speak(text);
                            setRobotChatMsg(text);
                        });
                    } else if (errorCode == 40002) {
                        runOnUiThread(() -> {
                            String text = getString(R.string.cannot_repeat_register);
                            speak(text);
                            setRobotChatMsg(text);
                        });
                    } else if (errorCode == 40003) {
                        runOnUiThread(() -> {
                            String text = getString(R.string.name_is_error);
                            speak(text);
                            setRobotChatMsg(text);
                        });
                    } else {
                        runOnUiThread(() -> {
                            String text = getString(R.string.register_faild_speak_text);
                            speak(text);
                            setRobotChatMsg(text);
                        });
                    }
                    if (errorCode != 0) {
                        runOnUiThread(() -> {
                            mPausePreview = false;
                            ll_register.setVisibility(View.GONE);
                            ll_take_photo.setVisibility(View.VISIBLE);
                            ll_complete_and_retake.setVisibility(View.GONE);
                            bt_take_photo.setVisibility(View.VISIBLE);
                            et_name.setText("");
                        });
                    }
                } catch (JSONException e) {
                    BlackgagaLogger.error(e.toString());
                }
            }
        });
        ServerFactory.getFaceInstance().faceRegSave(name);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        mRobotManager.cameraDisconnect(this);
    }

    @Override
    protected boolean onSpeechMessage(String text, String answerText) {
        if (super.onSpeechMessage(text, answerText)) {
            return false;
        }
        VipCenterAI.Intent intent = mAI.getIntent(text);
        if (intent != null) {
            mAI.handleIntent(intent);
        } else {
//            prattle(answerText);
        }
        return true;
    }
}
